<template>
	<div>
		<div class="select-box">
			<el-form :inline="true" :model="selectData" class="demo-form-inline">
				<el-form-item label="标题">
					<el-input v-model="selectData.title" placeholder="请输入关键字" />
				</el-form-item>
				<el-form-item label="详情">
					<el-input v-model="selectData.body" placeholder="请输入关键字" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<el-table :data="list[selectData.page - 1]" style="width: 100%">
			<el-table-column prop="id" label="ID" width="180" />
			<el-table-column prop="title" label="标题" width="180" />
			<el-table-column prop="body" label="详情" />
		</el-table>

		<el-pagination
			v-model:currentPage="selectData.page"
			v-model:page-size="selectData.pageSize"
			:page-sizes="[1, 2, 5, 10]"
			background
			layout="total, sizes, prev, pager, next, jumper"
			:total="selectData.total"
			@current-change="currentChange"
		>
		</el-pagination>
	</div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from 'vue'
import { InitData, ListInt } from '@/types/order'
import { getList } from '../http/api'
import _ from 'lodash'

export default defineComponent({
	setup() {
		const data = reactive(new InitData())
		let pageSize = data.selectData.pageSize

		onMounted(() => {
			getTheList()
		})

		// 获取数据并处理
		const getTheList = () => {
			getList({
				page: data.selectData.page,
				pageSize: data.selectData.pageSize
			}).then((res) => {
				console.log(res)
				data.selectData.total = res.data.length
				data.dataList = res.data
				sliceList(res.data)
			})
		}

		// 每页显示条数的改变
		// const sizeChange = (newSize: number, arr: ListInt[]) => {
		// 	data.selectData.pageSize = newSize
		// }

		//划分每页显示多少条数据
		const sliceList = (arr: ListInt[]) => {
			data.list = []
			for (let i = 0; i < arr.length; i += 10) {
				let list: any = arr.slice(i, i + 10)
				data.list.push(list)
			}
		}

		// 页码发生改变时  current-page 改变时触发
		const currentChange = (page: number) => {
			data.selectData.page = page
		}

		// 查询逻辑
		const onSubmit = () => {
			let arr: ListInt[] = []
			if (data.selectData.title || data.selectData.body) {
				if (data.selectData.title) {
					arr = data.dataList.filter(
						(v) => v.title.indexOf(data.selectData.title) != -1
					)
				}
				if (data.selectData.body) {
					arr = (data.selectData.title ? arr : data.dataList).filter(
						(v) => v.body.indexOf(data.selectData.body) != -1
					)
				}
			} else {
				arr = data.dataList
			}
			// console.log(arr)
			data.selectData.total = arr.length
			sliceList(arr)
		}

		return {
			...toRefs(data),
			currentChange,
			onSubmit
		}
	}
})
</script>

<style lang="scss" scoped>
.el-table {
	height: 78vh;
}
</style>
